package com.we.risk.logoff.userinfo;

import com.alibaba.fastjson.JSONObject;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

public class TableHhl01UserAccount {
    public static final String KFKTABLE = "fdm.hhl01_user_account";
    public static final String QUERYSQL =
            "select uid, "
                    + "account as register_mobile, "
                    + "system_unique_id as user_key, "
                    + "if(deleted_at is null, -1, deleted_at) as logoff_time, "
                    + "created_at as register_time, "
                    + "updated_at from "
                    + KFKTABLE;

    public long uid;
    public String register_mobile;
    public String user_key;
    public int logoff_time;
    public int register_time;
    public int updated_at;

    public TableHhl01UserAccount() {
    }

    public TableHhl01UserAccount(long uid, String register_mobile, String user_key,
                                 int logoff_time, int register_time, int updated_at) {
        this.uid = uid;
        this.register_mobile = register_mobile;
        this.user_key = user_key;
        this.logoff_time = logoff_time;
        this.register_time = register_time;
        this.updated_at = updated_at;
    }

    public static TableHhl01UserAccount init(long uid) {
        return new TableHhl01UserAccount(uid, "","",-1,0,0);
    }

    public static SingleOutputStreamOperator<String> getTableHhl01UserAccountStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableHhl01UserAccount.QUERYSQL);
        DataStream<Tuple2<Boolean, TableHhl01UserAccount>> inputStream =
                tableEnv.toRetractStream(tableRes, TableHhl01UserAccount.class);

        SingleOutputStreamOperator<String> out = inputStream.filter(new FilterFunction<Tuple2<Boolean, TableHhl01UserAccount>>() {
            @Override
            public boolean filter(Tuple2<Boolean, TableHhl01UserAccount> value) throws Exception {
                return value.f0;
            }
        }).uid("Hhl01UserAccount-filter")
                .keyBy(new KeySelector<Tuple2<Boolean, TableHhl01UserAccount>, Long>() {
                    @Override
                    public Long getKey(Tuple2<Boolean, TableHhl01UserAccount> value) throws Exception {
                        return value.f1.getUid();
                    }
                }).flatMap(new RichFlatMapFunction<Tuple2<Boolean, TableHhl01UserAccount>, String>() {
                    ValueState<TableHhl01UserAccount> tableHhl01UserAccountVState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        tableHhl01UserAccountVState = getRuntimeContext()
                                .getState(new ValueStateDescriptor<TableHhl01UserAccount>("TableHhl01UserAccountVState", TableHhl01UserAccount.class));
                    }

                    @Override
                    public void flatMap(Tuple2<Boolean, TableHhl01UserAccount> value, Collector<String> out) throws Exception {
                        long uid = value.f1.getUid();
                        int logoff_time = value.f1.getLogoff_time();
                        String register_mobile = value.f1.getRegister_mobile();
                        int updated_at = value.f1.getUpdated_at();
                        String user_key = value.f1.getUser_key();
                        int register_time = value.f1.getRegister_time();

                        TableHhl01UserAccount tmpState = tableHhl01UserAccountVState.value();
                        TableHhl01UserAccount curState = (tmpState == null ? init(uid) : tmpState);

                        if (updated_at > curState.getUpdated_at()) {
                            if (!user_key.equals(curState.getUser_key())
                                    || !register_mobile.equals(curState.getRegister_mobile())
                                    || register_time != curState.getRegister_time()
                                    || logoff_time != curState.getLogoff_time()) {
                                curState = value.f1;

                                JSONObject outJson = new JSONObject();
                                outJson.put("uid", uid);
                                outJson.put("user_key", user_key);
                                outJson.put("register_time", register_time);
                                outJson.put("logoff_time", (logoff_time == -1 ? null : logoff_time));
                                outJson.put("register_mobile", register_mobile);
                                out.collect(outJson.toString());
                            }

                            curState.updated_at = updated_at;
                            tableHhl01UserAccountVState.update(curState);
                        }

                    }
                });
        return out;
    }

    public long getUid() {
        return uid;
    }

    public String getRegister_mobile() {
        return register_mobile;
    }

    public String getUser_key() {
        return user_key;
    }

    public int getLogoff_time() {
        return logoff_time;
    }

    public int getRegister_time() {
        return register_time;
    }

    public int getUpdated_at() {
        return updated_at;
    }
}
